var iscrollobj = null;
//常量数据和定义菜单数据
    //单击后，按需加载

//定义模板 及相对应的数据绑定
function showLogin(){
    var sliderCount = 0;
    if($.trim($('.loginPanel [data-role=slider]').html())==''){
        berserker.xPost({url:'api/lg_slider.json',success:function(res){
            $('.loginPanel [data-role=slider]').html(template('tpl_lgSlider',res.data))

            $('.loginPanel .slidetabs').jcarousel({
              initCallback: function (carousel) {
                    var s ='';
                    sliderCount=carousel.list.context.childElementCount;
                    for(var i=0;i<sliderCount;i++){
                        s += '<a href="#" title="'+(i+1)+'"></a>';
                    }
                    jQuery('.login-slider .control_wrap').html(s);
                    jQuery('.login-slider .jcarousel-control a').bind('click', function() {
                        console.log(jQuery(this).attr('title'));
                        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('title')));
                        return false;
                    });
                },
                auto: 3,
                wrap: 'circular',
                scroll:1,
                animation:'slow',
                itemFirstInCallback:function(a1,a2,a3){
                    jQuery('.login-slider .jcarousel-control a.act').removeClass('act');
                    jQuery('.login-slider .jcarousel-control a:eq('+(a1.first%sliderCount-1)+')').addClass('act');
                },
                buttonNextHTML: null,
                buttonPrevHTML: null
            });
        }})
        $('.loginPanel [data-role=login]').click(function(evt){
            var pwd=$('[data-role=password]').val();
            if(pwd === ''){
                $.fallr('show', {
                    content : '<p>密码不能为空</p>',
                    autoclose : 2000,
                    useOverlay: false,
                    buttons:{}
                })
                return;
            }
            berserker.xPost({
                url:'/ipad/api/login.json',
                type:'get',
                data:{password:pwd},
                success:function(res){
                    if(res.code == 10000){
                        for(var p in res.data){
                            localStorage.setItem(p,res.data[p]);
                            $.cookie(p,res.data[p]);
                        }
                        showMain();
                    }else{
                        $.fallr('show', {
                            content : '<p>'+res.msg+'</p>',
                            autoclose : 3000,
                            useOverlay:false,
                            buttons:{}
                        })
                    }
                },error:function(){
                    //debugger;
                }
            })
        })
    }

      $('[data-role="username"]').val($.cookie('system_username_val'))
      $('.__frame').addClass('fr_login').removeClass('fr_main');
}
function showMain(){
    init();
    $('.__frame').addClass('fr_main');
}
function init(){
    berserker.getView('menu').render('#menuContainer',{
        list:[
            {name:'yypp',text:"医院品牌",act:1},
            {name:'hzmy',text:"患者满意"},
            {name:'mtbd',text:"媒体报道"},
            {name:'ztsj',text:"主题事件"},
            {name:'ylnc',text:"医疗内参"},
            {name:'qwbd',text:"权威报道"}
        ]
    })

    //绑定网络错误"重试"按钮事件
    domConfirmReTry.click(function(evt){
        domConfirmReTry.data('errored',true);
        intReLinkTimeSpan = new Date();
        $('#appriseMsg').html('正在尝试，请稍候......')
        domConfirmReTry.data('cbk').apply(domConfirmReTry.data('that'),domConfirmReTry.data('args'));
    })
    domConfirmClose.click(function(click){
        //隐藏右侧
        if(domRightContent.loader){
            domRightContent.loader.abort();
            domRightContent.loader = null;
            domRightLoading.hide();
        }
        //隐藏中间的加载层
        hideLoading();
        hideInternetError();
    })


    $('.__frame').click(function(evt){
        var parameter=''
            url = '';
        switch(evt.target.getAttribute('data-role')){
            case 'listing':
                if(evt.target.tagName === 'TD'){
                    var td = evt.target;
                        table = evt.target.parentNode.parentNode;
                    url = table.getAttribute('url')+ '?row='+$('td:first',td.parentNode).html()+'&col='+$('tr>td:gt('+td.cellIndex+')',table).html();
                    //berserker.log($('td:first',evt.target.parentNode).html() + $('tr>td:gt('+evt.target.cellIndex+')',evt.target.parentNode.parentNode).html())
                    break;
                }else{
                    url = evt.target.getAttribute('data-url');

                }
                showRight(url);
                //berserker.log('家在右侧')
                break;
            case 'webview':
                showWebView(evt.target.getAttribute('data-url'));
                break;
        }
    })

    //init网页预览 STSRT
    var webview = $('.webview'),
    webview_box= $('iframe',webview);


    webview_box.on('load',function(){
        domWebViewLoading.hide();
    })

    function showWebView(url){
        domWebViewLoading.show();
        webview.fadeIn(500);
        webview_box.attr('src',url || "http://www.baidu.com");
    }

    $('.webview_close').click(hideWebView);
    $('.webview_box').click(function(evt){
        if(evt.target.tagName !=='IFRAME'){
            hideWebView();
        }
    });

    function hideWebView(){
        domWebViewLoading.hide();
        webview.fadeOut(500);
    }
}
$(function(evt){
    $('body').bind('touchmove',function(evt){
        //event.preventDefault();
    })

    var code = location.search.replace(/\?.*?code\=([a-z,A-Z,0-9]+)/,'$1'),
        token = localStorage.getItem('token');
    //TODO验证是否
    $('.__frame').addClass('checking');
    //cookie失效,则重新绑定
    /*
    if(!$.cookie('system_username_val') || !$.cookie('system_rand_val')){
        $.fallr('show', {
            content : '<p>绑定被解除，请您联系信石科技的客户经理后再点击“申请绑定”</p><p data-role="tip" style="color:#be2d2d"></p>',
            buttons:{
                button1 : {text: '[重新绑定]', onclick: function(){
                    var btn = this;
                    berserker.xPost({url:'api/auth.php',type:'get',data:{act:'sys_bind','code':code},success:function(res){
                        if(res.code==10000 && $.cookie('system_username_val') && $.cookie('system_rand_val')){
                            $.fallr('hide',function(){
                                showLogin();
                                $.fallr('show', {
                                    content : '<p>请重新登陆!</p>',
                                    buttons:{
                                        button1 : {text: '确　定', onclick: function(){
                                            $.fallr('hide')
                                        }}
                                    }
                                })
                            });
                        }else{
                            $('[data-role=tip]',btn).html('请先联系产品经理后重试！');
                        }
                    },error:function(){
                        $('[data-role=tip]',btn).html('请先联系产品经理后重试！');
                    }})
                }},
            }
        });
        return;
    }
    */
    //验证token1
        showLogin();
return;
    if(!token){
        showLogin();
        return;
    }
    //验证token2
    berserker.xPost({url:'api/auth.php',data:{act:'login','token':token},success:function(res){
        if(res.code==10000){
            showMain();
        }else{
            showLogin();
            $.fallr('show', {
                content : '<p>'+res.msg+'</p>',
                buttons:{
                    button1 : {text: '确　定', onclick: function(){
                        $.fallr('hide')
                    }}
                }
            })
        }
    }})

    //验证token
    //如果cookie(system_username_val或system_rand_val)为空,则
//    localStorage.getItem();
//    localStorage.getItem
})

/*
    right content
*/

var domRightContent = $('#frm_right .content'),
    domRightTitle = $('#frm_right .title'),
    domRightTitletxt = $('#frm_right .title h3'),
    domConetntLoading = $('.shade-loading'),
    domWebViewLoading = $('.webview_loading'),
    domRightLoading = $('.right_loading'),
    domConfirmReTry = $('#confirmBox .aButtons-retry'),
    domConfirmClose = $('#confirmBox .aButtons-close'),
    intReLinkTimeSpan = 0;



function reinitRitBox(cfg){
    /*
    {
        pageurl:[string]分页加载路径
    }
    */
    domRightContent.data('page-index',cfg.pageIndex || 0);
    domRightContent.data('pageurl',cfg.pageurl);
}
function loadRight(pageIndex){
    showRight(domRightContent.data('pageurl'),{pageindex:pageIndex},pageIndex);
}
function hideRight(){
    domRightContent.html().fadeOut();
    domRightTitle.fadeOut();
    domRightTitletxt.html(res.data.title);
}
function showRight(url,data,pageIndex){
    if(domRightContent.loader){
         domRightContent.loader.abort();
    }
    domRightLoading.show();
    domRightContent.loader = berserker.getJSON(url,data,function(res){
        domRightLoading.hide();
        domRightContent.loader = null;
        //var nativeor = null
        //初始化 页码
        reinitRitBox({pageIndex:pageIndex,pageurl:res.data.pageurl});
        //渲染数据
        domRightContent.html('<div class="shadow"></div>'+res.data.html).fadeIn(function(){
        if(iscrollobj){
            iscrollobj = null;
        }
        iscrollobj = new iScroll(domRightContent[0]);
//            new iScroll('#frm_right');
        });
        domRightTitletxt.html(res.data.title);
        domRightTitle.fadeIn();

        //绑定chart
        $('[data-role=chart]', domRightContent).each(function(index,item){
            var cfg = res.data.chart[item.getAttribute('data-chart')];
            cfg.chart.renderTo = item;
            new Highcharts.Chart(cfg);
        })


        //重新绑定事件
        $('.navitator li',domRightContent).click(function(){
            var dataIndex = this.getAttribute('data-index');
            if(!dataIndex){return}
            switch(dataIndex){
                case 'pre':
                    if(domRightContent.data('page-index') == 0){
                        return;
                    }
                    loadRight(domRightContent.data('page-index')-1)
                    domRightContent.data('page-index',domRightContent.data('page-index')-1);
                    break;
                case 'next':
                    if(!$('[data-index='+(domRightContent.data('page-index')+1)+']',this.parentNode).size()){
                        return;
                    }
                    loadRight(domRightContent.data('page-index')+1)
                    domRightContent.data('page-index',domRightContent.data('page-index')+1);
                    break;
                default:
                    loadRight(dataIndex)
                    return;
            }
        })
    })
}
/*
    right content END
*/

/*
    加载中
*/
function showLoading(){
    domConetntLoading.fadeIn()
}
function hideLoading(){
    domConetntLoading.fadeOut()
}
/*
    加载中 END
*/
/*显示网络错误*/
function InternetError(jqXHR){
    var InterAvailable = jqXHR.status == 404 || jqXHR.status==500|| jqXHR.status==200;
    if(InterAvailable){
        domConfirmReTry.hide();
        domConfirmClose.show();
        $('#appriseMsg').html('很抱歉，服务器资源错误！')
    }else{
        domConfirmReTry.show();
        domConfirmClose.hide();
        $('#appriseMsg').html('很抱歉，网络通信异常，请确认互联网畅通后重试！')
    }
    domConfirmReTry.data('errored',false);
    $('#confirmBox').show();
}
function hideInternetError(){
    domConfirmReTry.data('errored',false);
    $('#confirmBox').hide();
}

/*
    center content
*/

/*
    center content END
*/